package com.jlnk.androidfmc.entity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Parcel;
import android.os.Parcelable;

import java.io.ByteArrayOutputStream;

public class News implements Parcelable {
    private String title;
    private String content;
    private byte[] imageBytes; // 存储图像字节数据
    private String image;


    // 构造函数
    public News() {
    }

    // 供系统使用，从Parcel中恢复对象
    protected News(Parcel in) {
        title = in.readString();
        content = in.readString();
        imageBytes = in.createByteArray();
    }

    // Getter和Setter
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }


    public byte[] getImageBytes() {
        return imageBytes;
    }

    public void setImageBytes(byte[] imageBytes) {
        this.imageBytes = imageBytes;
    }

    // 将字节数据转换为Bitmap
    // 注意：Parcelable不支持传递Bitmap对象，只传递字节数据
    public Bitmap getImage() {
        if (imageBytes != null && imageBytes.length > 0) {
            return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        }
        return null; // 如果没有图片数据，返回null
    }

    // 将Bitmap转换为字节数据
    public static byte[] convertBitmapToByteArray(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        return outputStream.toByteArray();
    }

    // Parcelable 接口实现部分
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(title);
        dest.writeString(content);
        dest.writeByteArray(imageBytes);
    }

    // Parcelable.Creator 实现，允许从Parcel中创建News对象
    public static final Parcelable.Creator<News> CREATOR = new Parcelable.Creator<News>() {
        @Override
        public News createFromParcel(Parcel in) {
            return new News(in);
        }

        @Override
        public News[] newArray(int size) {
            return new News[size];
        }
    };
    public String toJson() {
        return "{"
                + "\"title\": \"" + title + "\","
                + "\"image\": \"" + image + "\","
                + "\"content\": \"" + content + "\""
                + "}";
    }
    public void setImage(Bitmap bitmap) {
        this.imageBytes = convertBitmapToByteArray(bitmap); // 将 Bitmap 转换为字节数组
    }



}